package authorized

import (
	"encoding/json"
	"fmt"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
)

// QueryAuthApiList 调用方接口地址列表
// @Summary 调用方接口地址列表
// @Description 调用方接口地址列表
// @Tags API.authorized
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param businessKey query string true "businessKey"
// @Success 200 {object} response.TResponse{data=vo.AuthAPiVO}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/authorized_api [get]
// @Security LoginToken
func (a *authorizedController) QueryAuthApiList(c *gin.Context) {
	businessKey, exist := c.GetQuery("businessKey")
	fmt.Println("businessKey", businessKey, exist)
	if !exist {
		response.Fail(c, code.ParamBindError, code.Text(code.ParamBindError), gin.H{"realErr": "businessKey 必传"})
		return
	}
	res, err := a.authorizedService.QueryAuthApiList(c, businessKey)
	var api = make(map[string]interface{})
	apiStr, _ := json.Marshal(res)
	_ = json.Unmarshal(apiStr, &api)
	if err == nil {
		response.Success(c, "获取数据成功", api)
	}
}

// AddAuthorizedApi 授权调用方接口地址
// @Summary 授权调用方接口地址
// @Description 授权调用方接口地址
// @Tags API.authorized
// @Accept application/x-www-form-urlencoded
// @Produce json
// @Param businessKey formData string true "businessKey"
// @Param method formData string true "请求方法"
// @Param api formData string true "请求地址"
// @Success 200 {object} response.TResponse{data=interface{}}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/authorized_api [post]
// @Security LoginToken
func (a *authorizedController) AddAuthorizedApi(c *gin.Context) {
	var addApiReq QO.AddAuthApiReq
	if err := c.ShouldBind(&addApiReq); err != nil {
		response.Fail(c, code.ParamBindError, code.Text(code.ParamBindError), gin.H{"realErr": err})
		return
	}
	apiItem, err := a.authorizedService.AddAuthorizedApi(c, addApiReq)
	if err == nil {
		response.Success(c, "新增api数据成功", gin.H{
			"apiItem": apiItem,
		})
	}
}

// DeleteAuthorizedApi 删除调用方接口地址
// @Summary 删除调用方接口地址
// @Description 删除调用方接口地址
// @Tags API.authorized
// @Accept json
// @Produce json
// @Param id path string true "主键ID"
// @Success 200 {object} response.TResponse{data=interface{}}
// @Failure 400 {object}  response.TResponse{data=interface{}}
// @Router /api/authorized_api/{id} [delete]
// @Security LoginToken
func (a *authorizedController) DeleteAuthorizedApi(c *gin.Context) {
	id := c.Param("id")
	err := a.authorizedService.DeleteAuthorizedApi(c, id)
	if err == nil {
		response.Success(c, "删除api数据成功", gin.H{
			"id": id,
		})
	}
}
